package com.create404.suishoupai.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.create404.suishoupai.dto.EmployeeDto;
import com.create404.suishoupai.dto.LoginDto;
import com.create404.suishoupai.dto.UpdateInfoDto;
import com.create404.suishoupai.entity.Employee;
import com.create404.suishoupai.entity.EmployeeRole;
import com.create404.suishoupai.service.IEmployeeRoleService;
import com.create404.suishoupai.service.IEmployeeService;
import com.create404.suishoupai.utils.AesUtil;
import com.create404.suishoupai.utils.Result;
import com.create404.suishoupai.utils.SaltUtil;
import com.create404.suishoupai.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author create404
 * @since 2021-07-17
 */
@Api(tags = "员工接口")
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService iEmployeeService;

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private IEmployeeRoleService iEmployeeRoleService;


    @Value("${file.uploadurl}")
    private String uploadPath;

    @RequestMapping(value = {"/insert"}, method = RequestMethod.POST)
    public @ResponseBody
    Result insertSubmit(@RequestBody() Employee employee) {
        iEmployeeService.insert(employee);
        return Result.ok("提交成功");
    }

    @PostMapping("/login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "employeeId",value = "员工id",paramType = "query",required = true,dataType = "String"),
            @ApiImplicitParam(name = "password",value = "密码",paramType = "query",required = true,dataType = "String")
    })
    public Result login(@ApiParam(name = "登录对象",value = "登录用户的员工id和密码") @Validated @RequestBody LoginDto user, HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        String employeeId = AesUtil.aesDecrypt(user.getEmployeeId());
        String password = AesUtil.aesDecrypt(user.getPassword());
        Employee employee = iEmployeeService.getOne(new QueryWrapper<Employee>().eq("employee_id", employeeId));
        if (employee == null) {
            return Result.error("用户不存在");
        }

        String role = iEmployeeService.findRolesByEmployeeId(employeeId).getRoles().get(0).getName();
        Map<String, Object> map = new HashMap<>();
        try {
            subject.login(new UsernamePasswordToken(employeeId, password));
            response.addHeader("token", tokenUtil.getToken(employeeId, role));
            map.put("employeeId", employeeId);
            map.put("role", role);
            return Result.ok(map, "登录成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            Result.error("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            Result.error("密码错误");
        }
        return Result.error("操作错误");
    }

    @PostMapping("/register")
    public Result register(@Validated @RequestBody Employee employee) {
        Employee oriEmployee = iEmployeeService.getOne(new QueryWrapper<Employee>().eq("employee_id", employee.getEmployeeId()));
        if (oriEmployee != null) {
            return Result.error("员工号");
        }

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        iEmployeeService.register(employee);

        oriEmployee = iEmployeeService.getOne(new QueryWrapper<Employee>().eq("employee_id", employee.getEmployeeId()));

        EmployeeRole employeeRole = new EmployeeRole();
        employeeRole.setEmployeeid(oriEmployee.getId());
        employeeRole.setRoleid(3);

        iEmployeeRoleService.save(employeeRole);

        return Result.ok("注册成功");
    }


    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Employee> employees = iEmployeeService.selectAll();
        return Result.ok(employees);
    }

    @GetMapping("/selectDE")
    public Result selectDe() {
        Map<String, List<EmployeeDto>> employees = iEmployeeService.selectEDo();
        return Result.ok(employees);
    }

    @PostMapping("/saveAvatar")
    public Result saveAvatar(@RequestParam("file") MultipartFile file, Employee employee) {
        File filePath = new File(uploadPath);
        employee = iEmployeeService.getOne(new QueryWrapper<Employee>().eq("employee_id", employee.getEmployeeId()));
        String fileName = "";
        if (!filePath.isDirectory()) {
            //递归生成文件夹
            filePath.mkdirs();
        }
        if (file.isEmpty()) {
            return Result.error("保存失败");
        }
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        // new Date()为获取当前系统时间，也可使用当前时间戳
        String date = df.format(new Date());
        fileName = date + "-" + file.getOriginalFilename();
        File dest = new File(filePath, fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String avatarUrl = "http://39.105.110.122:8082/ssp/images/" + fileName;
        employee.setAvatar(avatarUrl);
        employee.setUpdateTime(LocalDateTime.now());
        boolean update = iEmployeeService.updateById(employee);
        if (update) {
            return Result.ok(avatarUrl, "头像保存成功");
        } else {
            return Result.error("头像保存失败");
        }
    }

    @PostMapping("/getInform")
    public Result getInform(String employeeId, HttpServletResponse response) {
        Employee employee = iEmployeeService.getOne(new QueryWrapper<Employee>().eq("employee_id", employeeId));
        employee.setPassword("");
        employee.setSalt("");
        return Result.ok(employee, "获取成功");
        // return Result.ok("test");
    }

    @GetMapping("/logout")
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.ok("退出登录成功");
    }

    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody UpdateInfoDto updateInfoDto) {

        String oriPassword = AesUtil.aesDecrypt(updateInfoDto.getOriPassword());
        String newPassword = AesUtil.aesDecrypt(updateInfoDto.getNewPassword());
        String employeeId = updateInfoDto.getEmployeeId();

        Employee employee = iEmployeeService.getOne(new QueryWrapper<Employee>().eq("employee_id", employeeId));

        Md5Hash md5Hash = new Md5Hash(oriPassword, employee.getSalt(), 1024);

        oriPassword = md5Hash.toHex();


        if (!oriPassword.equals(employee.getPassword())) {
            return Result.ok("原始密码错误");
        }

        String salt = SaltUtil.getSalt(8);
        newPassword = new Md5Hash(newPassword, salt, 1024).toHex();
        employee.setPassword(newPassword);
        employee.setSalt(salt);
        boolean update = iEmployeeService.updateById(employee);
        if (update) {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return Result.ok("密码修改成功");
        } else {
            return Result.error("密码修改失败");
        }

    }

    @PostMapping("/updatePasswordbyPhone")
    public Result updatePasswordbyPhone(@RequestBody UpdateInfoDto updateInfoDto) {

        String newPassword = AesUtil.aesDecrypt(updateInfoDto.getNewPassword());

        String phone = updateInfoDto.getPhone();

        Employee employee = iEmployeeService.getOne(new QueryWrapper<Employee>().eq("phone", phone));

        if (employee != null) {
            String salt = SaltUtil.getSalt(8);
            newPassword = new Md5Hash(newPassword, salt, 1024).toHex();
            employee.setPassword(newPassword);
            employee.setSalt(salt);
            boolean update = iEmployeeService.updateByPhone(employee);
            if (update) {
                return Result.ok("密码修改成功");
            } else {
                return Result.error("密码修改失败");
            }
        } else {
            return Result.error("无此账号");
        }

    }


    @PostMapping("/updatePhone")
    public Result updatePhone(@RequestBody UpdateInfoDto updateInfoDto) {

        String phone = AesUtil.aesDecrypt(updateInfoDto.getPhone());
        String employeeId = updateInfoDto.getEmployeeId();
        Employee employee = iEmployeeService.getOne(new QueryWrapper<Employee>().eq("employee_id", employeeId));

        employee.setPhone(phone);

        boolean update = iEmployeeService.updateById(employee);
        if (update) {
            return Result.ok("手机号修改成功");
        } else {
            return Result.error("手机号修改失败");
        }
    }


}
